package com.feilong.modules.controller.user;

import com.feilong.modules.common.exception.APIException;
import com.feilong.modules.model.user.constant.UserInfoConstant;
import com.feilong.modules.model.user.request.LoginRequest;
import com.feilong.modules.model.user.vo.UserInfoVO;
import com.feilong.modules.service.user.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 用户登录
     * @param userInfo
     * @return
     */
    @PostMapping("login")
    public UserInfoVO login(@RequestBody @Valid LoginRequest userInfo){
        return userInfoService.login(userInfo);
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @PostMapping("getUserInfo")
    public UserInfoVO getUserInfo(HttpServletRequest request){
        String token = request.getHeader(UserInfoConstant.HEADERS_TOKEN);
        if (StringUtils.isBlank(token)) {
            throw new APIException(UserInfoConstant.INVALID_TOKEN);
        }
        return userInfoService.getUserInfo(token);
    }

    /**
     * 用户退出登录
     * @param request
     */
    @GetMapping("loginOut")
    public void loginOut(HttpServletRequest request){
        String token = request.getHeader(UserInfoConstant.HEADERS_TOKEN);
        if (StringUtils.isBlank(token)) {
            throw new APIException(UserInfoConstant.LOGIN_OUT_FAIL);
        }
        userInfoService.loginOut(token);
    }
}
